﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using RebellionII.GUI;
using RebEngine;
using RebEngine.GameComponents;
using RebEngine.Managers;
using RebellionII.GameObjects;

namespace RebellionII.GameScreens
{
    enum SelectedOption
    {
        New = 0,
        Load = 1,
        Option = 2,
        Exit = 3,
    }

    public class MainMenuScreen : GameScreen
    {
        const string texture = "background";
        SelectedOption currentSelection = new SelectedOption();
        Color cNew, cLoad, cOption, cExit;

        InputWindow basicInputWindow;
        MessageWindow newWindow;
        TeamSelection teamSelection;

        Timer checkedSettingsChanged;
        
        float tempFloat;
        /// <summary>
        /// Constructor
        /// </summary>
        public MainMenuScreen()
        {
            Timer tTimer = new Timer();
            checkedSettingsChanged = new Timer();

            TransitionOnTime = TimeSpan.FromSeconds(1.0f);
            TransitionOffTime = TimeSpan.FromSeconds(1.0f);
            currentSelection = SelectedOption.New;
            tTimer.Start(0.75, false);
            
            tTimer.TimerFinished += new Timer.Fire(tTimer_TimerFinished);
        }

        void tTimer_TimerFinished()
        {
            InputManager.Manager.Input.KeyPress += new TomShane.Neoforce.Controls.KeyEventHandler(Input_KeyPress);
            InputManager.Manager.Input.MousePress += new TomShane.Neoforce.Controls.MouseEventHandler(Input_MousePress);
        }

        void Input_MousePress(object sender, TomShane.Neoforce.Controls.MouseEventArgs e)
        {
            if ((e.Position.X > 75) && (e.Position.X < 255))
            {
                int y = e.Position.Y;

                if ((y < 400) && (y > 325))
                {
                    newWindow = new MessageWindow("Would you like to start a new game or join someone?", "New", "Join");
                    newWindow.btn1.Click += new TomShane.Neoforce.Controls.EventHandler(NewGameGUI);
                    newWindow.btn2.Click += new TomShane.Neoforce.Controls.EventHandler(JoinGameGUI);
                }
                if ((y < 500) && (y > 425))
                { }
                if ((y < 600) && (y > 525))
                { }
                if ((y < 700) && (y > 625))
                {
                    EngineManager.Game.Exit(); 
                }
            }
        }

        public override void LoadContent()
        {
            base.LoadContent();
            TextureManager.AddTexture("AllianceSymbol");
            TextureManager.AddTexture("EmpireSymbol");
            TextureManager.AddTexture(texture);
        }

        public override void UnloadContent()
        {
            base.UnloadContent();
        }

        public override void Initialize()
        {
            
        }
       
        void Input_KeyPress(object sender, TomShane.Neoforce.Controls.KeyEventArgs e)
        {
            if (e.Key == Keys.Down)
            {
                if (currentSelection == SelectedOption.Exit)
                    currentSelection = SelectedOption.New;
                else
                    currentSelection += 1;
            }
            if (e.Key == Keys.Up)
            {
                if (currentSelection == SelectedOption.New)
                    currentSelection = SelectedOption.Exit;
                else
                    currentSelection -= 1;
            }

            if (e.Key == Keys.Enter)
            {
                switch (currentSelection)
                {
                    case SelectedOption.New:
                            newWindow = new MessageWindow("Would you like to start a new game or join someone?", "New", "Join");
                            
                            newWindow.btn1.Click += new TomShane.Neoforce.Controls.EventHandler(NewGameGUI);
                            newWindow.btn2.Click += new TomShane.Neoforce.Controls.EventHandler(JoinGameGUI);
                        break;
                    case SelectedOption.Load:
                        break;
                    case SelectedOption.Option:
                        break;
                    case SelectedOption.Exit:
                        EngineManager.Game.Exit(); 
                        break;
                }

            }
        }

        void NewGameGUI(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            teamSelection = new TeamSelection(false);
            teamSelection.ButtonOne.Enabled = false;
            newWindow.Close();
            NetClientManager.Connect("localhost", EngineManager.Settings.NetPort);

            checkedSettingsChanged.Start(1.0, true);
            checkedSettingsChanged.TimerFinished += new Timer.Fire(SendLatestGameUpdate);
            teamSelection.ButtonTwo.Click += new TomShane.Neoforce.Controls.EventHandler(BeginGame);
            teamSelection.ButtonOne.Click += new TomShane.Neoforce.Controls.EventHandler(ButtonOne_Click);
        }

        void SendLatestGameUpdate()
        {
            NetServerManager.SendServerSettings(teamSelection.lblplayerOne.Text, teamSelection.lblPlayerTwo.Text,
                                                teamSelection.cmbCoreMax.Text, teamSelection.cmbCoreMin.Text,
                                                teamSelection.cmbMidMax.Text, teamSelection.cmbMidMin.Text,
                                                teamSelection.cmbRimMax.Text, teamSelection.cmbRimMin.Text,
                                                teamSelection.cmbFacilityBonus.Text, teamSelection.cmbShipBonus.Text,
                                                teamSelection.cmbJediBonus.Text, teamSelection.cmbTroopBonus.Text,
                                                teamSelection.cmbTeamFavoured.Text, teamSelection.cmbShipBonus.Text,
                                                teamSelection.chkDblStartingPlanets.Checked);
        }

        void ButtonOne_Click(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            InputManager.Manager.Remove(teamSelection.MainWindow);
            teamSelection.MainWindow.Visible = false;
            NetClientManager.Client.Disconnect("Closing Connection");
            checkedSettingsChanged.Stop();
        }

        // Is called when the Server clicks Generate and then begins the game
        void BeginGame(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            EngineManager.Settings.CoreMaxFacilities = Convert.ToInt32(teamSelection.cmbCoreMax.Text);
            EngineManager.Settings.MidMaxFacilities = Convert.ToInt32(teamSelection.cmbMidMax.Text);
            EngineManager.Settings.RimMaxFacilities = Convert.ToInt32(teamSelection.cmbRimMax.Text);
            EngineManager.Settings.CoreMinFacilities = Convert.ToInt32(teamSelection.cmbCoreMin.Text);
            EngineManager.Settings.MidMinFacilities = Convert.ToInt32(teamSelection.cmbMidMin.Text);
            EngineManager.Settings.RimMinFacilities = Convert.ToInt32(teamSelection.cmbRimMin.Text);

            EngineManager.Settings.ChanceFacilityBonus = Convert.ToInt32(teamSelection.cmbFacilityBonus.Text);
            EngineManager.Settings.ChanceTroopBonus = Convert.ToInt32(teamSelection.cmbTroopBonus.Text);
            EngineManager.Settings.ChanceShipBonus = Convert.ToInt32(teamSelection.cmbShipBonus.Text);
            EngineManager.Settings.ChanceJediBonus = Convert.ToInt32(teamSelection.cmbJediBonus.Text);

            EngineManager.Settings.DoubleStartingPlanets = teamSelection.chkDblStartingPlanets.Checked;

            switch (teamSelection.cmbTeamFavoured.Text)
            {
                case "Empire":
                    EngineManager.Settings.TeamFavoured = TeamName.Empire;
                    break;
                case "Alliance":
                    EngineManager.Settings.TeamFavoured = TeamName.Alliance;
                    break;
                default:
                    EngineManager.Settings.TeamFavoured = TeamName.Default;
                    break;
            }
           
            NetServerManager.GenerateUniverse();
            NetServerManager.SendGeneratedUniverse();
            teamSelection.MainWindow.Close();
            ScreenManager.AddScreen(new LoadingScreen());
            InputManager.Manager.Input.KeyPress -= Input_KeyPress;
            MoveToGame();
            checkedSettingsChanged.Stop();
        }

        // Is called when you select to join another game and prompts for IP
        void JoinGameGUI(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            basicInputWindow = new InputWindow("Please enter the IP Address:", "Join", "Cancel");
            basicInputWindow.btn1.Click += new TomShane.Neoforce.Controls.EventHandler(AttemptJoin);
            newWindow.Close();
            basicInputWindow.MainWindow.Close();
        }

        // Attempts to join based on given IP. Creates a teamselection window based on Settings set and then 
        // will wait for server to start the game.
        void AttemptJoin(object sender, TomShane.Neoforce.Controls.EventArgs e)
        {
            throw new NotImplementedException("Need to add a Join string to AttemptJoin");
            //if(true)//need to test to make sure connection is created then get current Settings of the server.
            //{
             //   basicInputWindow.MainWindow.Close();
             //   teamSelection = new TeamSelection(true);
            //}
        }

        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                      bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, false);
            tempFloat = (float)Math.Sin(gameTime.TotalGameTime.TotalSeconds * 4) / 4;
            tempFloat += (float)0.75;

            switch (currentSelection)
            {
                case SelectedOption.New:
                    cNew = new Color(new Vector4(Color.Yellow.ToVector3(), tempFloat));
                    cOption = Color.White; cLoad = Color.White; cExit = Color.White;
                    break;
                case SelectedOption.Load:
                    cOption = Color.White; cNew = Color.White; cExit = Color.White;
                    cLoad = new Color(new Vector4(Color.Yellow.ToVector3(), tempFloat));
                    break;
                case SelectedOption.Option:
                    cLoad = Color.White; cNew = Color.White; cExit = Color.White;
                    cOption = new Color(new Vector4(Color.Yellow.ToVector3(), tempFloat));
                    break;
                case SelectedOption.Exit:
                    cOption = Color.White; cNew = Color.White; cLoad = Color.White;
                    cExit = new Color(new Vector4(Color.Yellow.ToVector3(), tempFloat));
                    break;
            }

            if (teamSelection != null)
            {
                if (NetServerManager.Server.ConnectionsCount == 0)
                {
                    teamSelection.ButtonOne.Enabled = false;
                }
                else
                {
                    teamSelection.ButtonOne.Enabled = true;
                }
            }
        }

        public override void Draw(GameTime gameTime)
        {
            EngineManager.Device.Clear(Color.Black);
            
            Viewport viewport = EngineManager.Device.Viewport;
            
            Rectangle fullscreen = new Rectangle(0, 0, viewport.Width, viewport.Height);

            byte fade = TransitionAlpha;

            ScreenManager.SpriteBatch.Begin();
            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture(texture).BaseTexture as Texture2D,
                                           fullscreen,
                                           new Color(fade, fade, fade));
            
            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, new Rectangle(75, 325, 180, 75), Color.Red);
            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, new Rectangle(80, 330, 170, 65), Color.Black);
            ScreenManager.SpriteBatch.DrawString(ScreenManager.Font, "New Game", new Vector2(100, 350), cNew);

            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, new Rectangle(75, 425, 180, 75), Color.Red);
            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, new Rectangle(80, 430, 170, 65), Color.Black);
            ScreenManager.SpriteBatch.DrawString(ScreenManager.Font, "Load Game", new Vector2(100, 450), cLoad);

            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, new Rectangle(75, 525, 180, 75), Color.Red);
            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, new Rectangle(80, 530, 170, 65), Color.Black);
            ScreenManager.SpriteBatch.DrawString(ScreenManager.Font, "Options", new Vector2(100, 550), cOption);

            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, new Rectangle(75, 625, 180, 75), Color.Red);
            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, new Rectangle(80, 630, 170, 65), Color.Black);
            ScreenManager.SpriteBatch.DrawString(ScreenManager.Font, "Exit", new Vector2(100, 650), cExit);

            ScreenManager.SpriteBatch.End();
        }

        private void MoveToGame()
        {
            if (basicInputWindow != null)
            {
                InputManager.Manager.Remove(basicInputWindow.MainWindow);
            }

            if (teamSelection != null)
            {
                InputManager.Manager.Remove(teamSelection.MainWindow);
            }

            if (newWindow != null)
            {
                InputManager.Manager.Remove(newWindow);
            }

            InputManager.Manager.Input.KeyPress -= Input_KeyPress;
        }
    }
}